package com.example.client.socket;

import com.example.client.game.GomokuState;
import com.example.client.ui.GamePanel1;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.example.client.game.SnakeState;
import com.example.client.ui.GamePanel;
import lombok.Getter;
import lombok.Setter;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

@Setter
@Getter
public class GameWebSocketClient1 extends WebSocketClient {
    private String sessionId;
    private GamePanel1 gamePanel1;
    private final ObjectMapper mapper = new ObjectMapper();

    public GameWebSocketClient1(URI serverUri, GamePanel1 gamePanel1) {
        super(serverUri);
        this.gamePanel1 = gamePanel1;
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        System.out.println("Connected to server");  //当成功连接到服务器时调用，输出连接成功信息
    }

    @Override
    public void onMessage(String message) {
        try {
            GomokuState state = mapper.readValue(message, GomokuState.class);
            gamePanel1.updateGameState(state);  //当收到服务器消息时调用，将 JSON 消息转换为 GomokuState 对象并更新游戏面板
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {  //当连接关闭时调用，输出断开连接信息
        System.out.println("Disconnected: " + reason);
    }

    @Override
    public void onError(Exception ex) {
        System.err.println("Error: " + ex.getMessage());    //当连接错误时调用，输出断开错误信息
    }

    // 发送下棋请求
    public void sendMove(int row, int col) {
        try {
            String moveJson = mapper.writeValueAsString(new MoveRequest(row, col));
            send(moveJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 内部类：表示下棋请求
    public static class MoveRequest {  // 添加public修饰符
        public int row;  // 改为公共字段
        public int col;

        public MoveRequest(int row, int col) {
            this.row = row;
            this.col = col;
        }

        // 添加getter方法
        public int getRow() { return row; }
        public int getCol() { return col; }
    }

}